#include "myfilewg.h"
#include "ui_myfilewg.h"
#include "common/downloadtask.h"
#include "common/logininfoinstance.h"
#include "selfwidget/filepropertyinfo.h"
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonArray>
#include<QFileDialog>
#include<QMessageBox>
#include<QNetworkReply>
#include<QHttpPart>
#include<QStringList>
#include<QString>
#include <QTimer>
#include <QNetworkAccessManager>

MyFileWg::MyFileWg(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyFileWg)
{
    ui->setupUi(this);

    // 初始化listWidget文件列表
    initListWidget();
    // 添加右键菜单
    addActionMenu();
    // http管理类对象
    m_manager = Common::getNetManager();

    //
    checkTaskList();
}

MyFileWg::~MyFileWg()
{
    delete ui;
}

//初始化文件列表
void MyFileWg::initListWidget()
{
    //设置图标尺寸
    ui->listWidget->setViewMode(QListView::IconMode);
    ui->listWidget->setIconSize(QSize(80,80));
    ui->listWidget->setGridSize(QSize(100,120));
    //设置跟随大小改变，自动适应布局
    ui->listWidget->setResizeMode(QListView::Adjust);
    //设置列表可以拖动，
    ui->listWidget->setMovement(QListView::Static);
    //设置图标间距离
    ui->listWidget->setSpacing(30);

    //
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->listWidget,&QListWidget::customContextMenuRequested,this,&MyFileWg::showmenu);
    //获取点击的item，并判断是不是图标中的“上传文件”
    connect(ui->listWidget,&QListWidget::itemPressed,this,[=](QListWidgetItem * item)
    {
        QString str = item->text();
        if("上传文件" == str)
        {
            addUploadFiles();
        }
    });
}
//创建右键菜单，添加动作，绑定connect
void MyFileWg::addActionMenu()
{
    //菜单一：在图标上右键时显示的菜单
    m_menu= new MyMenu(this);
    m_downloadAction = new QAction("下载",this);
    m_shareAction    = new QAction("分享",this);
    m_delAction      = new QAction("删除",this);
    m_propertyAction = new QAction("属性",this);

    m_menu->addAction(m_downloadAction);
    m_menu->addAction(m_shareAction);
    m_menu->addAction(m_delAction);
    m_menu->addAction(m_propertyAction);

    //菜单二：在空白处右键时显示的菜单
    m_menuEmpty = new MyMenu(this);
    m_pvAscendingAction  = new QAction("按下载量升序排列",this);
    m_pvDescendingAction = new QAction("按下载量降序排列",this);
    m_refreshAction      = new QAction("刷新",this);
    m_uploadAction       = new QAction("上传",this);

    m_menuEmpty->addAction(m_pvAscendingAction);
    m_menuEmpty->addAction(m_pvDescendingAction);
    m_menuEmpty->addAction(m_refreshAction);
    m_menuEmpty->addAction(m_uploadAction);

    //给前面八个动作添加信号和槽
    connect(m_downloadAction,&QAction::triggered,[=](){addDownloadFiles();});
    connect(m_shareAction,&QAction::triggered,[=](){dealSelectdFile("分享");});
    connect(m_delAction,&QAction::triggered,[=](){dealSelectdFile("删除");});
    connect(m_propertyAction,&QAction::triggered,[=](){dealSelectdFile("属性");});

    connect(m_pvAscendingAction,&QAction::triggered,[=](){refreshFiles(PvAsc);});
    connect(m_pvDescendingAction,&QAction::triggered,[=](){refreshFiles(PvDesc);
        qDebug()<<"refreshFiles(PvDesc);";
    });
    connect(m_refreshAction,&QAction::triggered,[=](){refreshFiles();});
    connect(m_uploadAction,&QAction::triggered,[=](){addUploadFiles();});
}

// 设置md5信息的json包
QByteArray MyFileWg::setMd5Json(QString user, QString token, QString md5, QString fileName)
{
    QMap<QString,QVariant> tmp;
    tmp.insert("user",user);
    tmp.insert("token",token);
    tmp.insert("md5",md5);
    tmp.insert("fileName",fileName);
    //#include<QJsonDocument>
    QJsonDocument json = QJsonDocument::fromVariant(tmp);
    if(json.isNull())
    {
        return "";
    }
    return json.toJson();
}
//上传文件处理，取出上传任务列表的队首任务，上传完后，再取下一个任务
void MyFileWg::uploadFilesAction()
{
    //获取上传单例
    UploadTask * uploadList = UploadTask::getInstance();
    //
    if(NULL == uploadList)
    {
        return;
    }
    if(uploadList->isEmpty())
    {
        return;
    }
    if(uploadList->isUpload())
    {
        return;
    }

    //
    LoginInfoInstance *login = LoginInfoInstance::getInstance();
    QNetworkRequest request;
    QString url = QString("http://%1:%2/md5").arg(login->getIp()).arg(login->getPort());
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    UploadFileInfo *info = uploadList->takeTask();
    //
    QByteArray array = setMd5Json(login->getUser(),login->getToken(),info->md5,info->fileName);
    QNetworkReply *reply = m_manager->post(request,array);
    if(NULL == reply)
    {
        return;
    }

    //
    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(reply->error() != QNetworkReply::NoError)
        {
            reply->deleteLater();
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();

        if("006" == m_cm.getCode(array))
        {
            m_cm.writeRecord(login->getUser(),info->fileName,"006");
            uploadList->dealUploadTask();
        }
        else if("007" == m_cm.getCode(array))
        {
            uploadFile(info);//进行真正上传。
        }
        else if("005" == m_cm.getCode(array))
        {
            m_cm.writeRecord(login->getUser(),info->fileName,"005");
        }
        else if("111" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"账户异常","请重新登陆！！！");
            emit loginAgainSignal();
            return;
        }
    });
}
//进行真正的上传
void MyFileWg::uploadFile(UploadFileInfo *info)
{
    QFile *file = info->file;
    QString fileName = info->fileName;
    QString md5 = info->md5;
    qint64 size = info->size;
    DataProgress *dp = info->dp;//进度条
    QString boundary = m_cm.getBoundary();//分割线

    LoginInfoInstance *login = LoginInfoInstance::getInstance();

    QHttpPart part;
    QString disp = QString("from-data; user=\"%1\"; filename=\"%2\"; md5=\"%3\"; size=%4")
                       .arg(login->getUser()).arg(info->fileName).arg(info->md5).arg(info->size);
    part.setHeader(QNetworkRequest::ContentDispositionHeader,disp);
    part.setHeader(QNetworkRequest::ContentTypeHeader,"image/png");
    part.setBodyDevice(info->file);
    QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType,this);
    multipart->append(part);

    QNetworkRequest request;
    QString url = QString("http://%1:%2/upload").arg(login->getIp()).arg(login->getPort());
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"multipart/fron-data");
    QNetworkReply *reply = m_manager->post(request,multipart);
    if(NULL == reply)
    {
        return;
    }

    connect(reply,&QNetworkReply::uploadProgress,[=](qint64 bytesRead,qint64 totalBytes)
    {
        if(0 != totalBytes)
        {
            dp->setProgress(bytesRead/1024,totalBytes/1024);//进度条
        }
    });

    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(QNetworkReply::NoError != reply->error())
        {
            qDebug()<<reply->errorString();
            reply->deleteLater();
            m_cm.writeRecord(login->getUser(),info->fileName,"009");
            UploadTask *uploadList = UploadTask::getInstance();
            uploadList->dealUploadTask();
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();
        multipart->deleteLater();

        if("008" == m_cm.getCode(array))
        {
            m_cm.writeRecord(login->getUser(),info->fileName,"008");//上传成功
        }
        else if("009" == m_cm.getCode(array))
        {
            m_cm.writeRecord(login->getUser(),info->fileName,"009");
        }
        UploadTask *uploadList = UploadTask::getInstance();
        if(NULL == uploadList)
        {
            qDebug()<<"UploadTask::getInstance() == NULL";
            return;
        }
        uploadList->dealUploadTask();
    });
}
//清空文件列表
void MyFileWg::clearFileList()
{
    int num = m_fileList.size();
    for(int i = 0;i < num;++i)
    {
        FileInfo * tmp = m_fileList.takeFirst();
        delete tmp;
    }
}
//清空当前item
void MyFileWg::clearItems()
{
    int n = ui->listWidget->count();
    for(int i = 0;i<n;++i)
    {
        QListWidgetItem *item = ui->listWidget->takeItem(0);
        delete item;
    }
}
//单独添加“上传文件”的图标
void MyFileWg::addUploadItem(QString iconPath, QString name)
{
    ui->listWidget->addItem(new QListWidgetItem(QIcon(iconPath),name));
}
//刷新显示文件列表信息的item
void MyFileWg::refreshFileItems()
{
    clearItems();//清空全部item图标
    if(m_fileList.isEmpty() == false)
    {
        int n = m_fileList.size();//
        for(int i = 0;i < n;++i)
        {
            FileInfo *tmp = m_fileList.at(i);
            QListWidgetItem *item = tmp->item;
            ui->listWidget->addItem(item);
        }
    }
    this->addUploadItem();//添加“上传文件图标”
}
// 设置获取服务器文件信息的json包
QByteArray MyFileWg::setFilesListJson(QString user, QString token, int start, int count)
{
    QMap<QString,QVariant> tmp;
    tmp.insert("user",user);
    tmp.insert("token",token);
    tmp.insert("start",start);
    tmp.insert("count",count);
    QJsonDocument json = QJsonDocument::fromVariant(tmp);
    if(json.isNull())
    {
        return "";
    }
    return json.toJson();
}
//获取新的文件列表信息
void MyFileWg::getUserFilesList(MyFileWg::Display cmd)
{
/**/
    if(m_userFilesCount <= 0)
    {
        refreshFileItems();//此时说明不需要再去访问服务器和接收服务器传来的消息，设置完图标后就可直接退出
        return;
    }
    if(m_count > m_userFilesCount)
    {
        m_count = m_userFilesCount;//如果剩余文件数量小于每次传输的文件数量则将剩余文件数量赋值给下次传输文件的数量
    }
    QNetworkRequest request;
    LoginInfoInstance *login = LoginInfoInstance::getInstance();//获取登录信息单例
    QString type;
    if(Normal == cmd)
    {
        type = "normal";
    }
    else if(PvAsc == cmd)
    {
        type = "pvasc";
    }
    else if(PvDesc == cmd)
    {
        type = "pvdesc";
    }
    QString url;
    url = QString("http://%1:%2/myfiles?cmd=%3").arg(login->getIp()).arg(login->getPort()).arg(type);
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QByteArray data = setFilesListJson(login->getUser(),login->getToken(),m_start,m_count);
    m_start += m_count;//更新文件列表起始位置
    m_userFilesCount -= m_count;//更新剩余未获取的文件信息数量
    QNetworkReply * reply = m_manager->post(request,data);
    if(NULL == reply)
    {
        return;//
    }
    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(QNetworkReply::NoError != reply->error())
        {
            reply->deleteLater();//释放资源，退出
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();//释放
        if("111" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"账户异常","请重新登录！！！");
            emit loginAgainSignal();
            return;//验证失败，退出重新登录
        }
        if("015" != m_cm.getCode(array))
        {
            getFileJsonInfo(array);//解析json信息，存放起来
            getUserFilesList(cmd);//调用自身，继续获取用户文件列表资料
        }
    });
}
//解析并存放来自服务器的文件信息json,
void MyFileWg::getFileJsonInfo(QByteArray data)
{
    QJsonParseError error;//
    QJsonDocument doc = QJsonDocument::fromJson(data,&error);
    if(QJsonParseError::NoError == error.error)
    {
        if(doc.isNull() || doc.isEmpty())
        {
            return;//空，返回
        }
        if(doc.isObject())
        {
            QJsonObject obj = doc.object();//
            QJsonArray array = obj.value("file").toArray();//#include<QJsonArray>
            int size = array.size();
            for(int i = 0;i < size;++i)
            {
                QJsonObject tmp = array[i].toObject();//
                FileInfo *info = new FileInfo;
                info->user = tmp.value("user").toString();
                info->md5 = tmp.value("md5").toString();
                info->time = tmp.value("time").toString();
                info->filename = tmp.value("filename").toString();
                info->shareStatus = tmp.value("share_status").toInt();
                info->pv = tmp.value("pv").toInt();
                info->url = tmp.value("url").toString();
                info->size = tmp.value("size").toInt();
                info->type = tmp.value("type").toString();
                QString type = info->type + ".png";
                info->item = new QListWidgetItem(QIcon(m_cm.getFileType(type)),info->filename);

                m_fileList.append(info);
            }
        }
    }
    else
    {
        qDebug()<<"void MyFileWg::getFileJsonInfo(QByteArray data)"<<error.errorString();
    }
}
//刷新列表，发送的json包
QByteArray MyFileWg::setGetCountJson(QString user, QString token)
{
    QMap<QString,QVariant> tmp;
    tmp.insert("user",user);
    tmp.insert("token",token);
    QJsonDocument json = QJsonDocument::fromVariant(tmp);
    if(json.isEmpty())
    {
        return "";
    }
    return json.toJson();
}
//得到服务器关于文件数量的json
QStringList MyFileWg::getCountStatus(QByteArray json)
{
    QJsonParseError error;
    QStringList list;
    QJsonDocument jsond = QJsonDocument::fromJson(json,&error);
    if(QJsonParseError::NoError == error.error)
    {
        if(jsond.isNull() || jsond.isEmpty())
        {
            return list;//返回是空的
        }
        if(jsond.isObject())
        {
            QJsonObject obj = jsond.object();//取得外层大对象#include<QJsonObject>
            list.append(obj.value("token").toString());//登录的token
            list.append(obj.value("num").toString());//文件个数
        }
    }
    else
    {
        qDebug()<<"err = "<<error.errorString();
    }
    return list;
}

// 添加需要下载的文件到下载任务列表
void MyFileWg::addDownloadFiles()
{
    //添加信号
    emit gotoTransfer(TransferStatus::Download);
    QListWidgetItem *item = ui->listWidget->currentItem();
    if(NULL == item)
    {
        return;//说明点击到的不是文件，但前面做了判断，这里应该不会触发
    }
    //获取下载实例#include "common/downloadtask.h"
    DownloadTask *p = DownloadTask::getInstance();
    if(NULL == p)
    {
        return;//获取对象失败，返回
    }
    //寻找是列表中的那个item对象，从而获取到文件名和其他后面需要的信息
    for(int i = 0;i < m_fileList.size();++i)
    {
        //判断是其中哪个item，然后用m_filelist去获取其信息
        if(m_fileList.at(i)->item == item)
        {
            //设置下载的路径和文件名
            QString filePathName = QFileDialog::getSaveFileName(this,"",m_fileList.at(i)->filename);
            //判断路径是否适合
            if(filePathName.isEmpty())
            {
                return;
            }
            //讲文件追加到下载列表中，并通过追加函数返回值确认是否添加成功，-1代表下载任务已存在，-2代表打开文件失败，之后中断循环
            int ret = p->appendDownloadList(m_fileList.at(i),filePathName);
            if(-1 == ret)
            {
                QMessageBox::warning(this, "任务已存在", "任务已经在下载队列中！！！");
            }
            else if(-2 == ret)
            {
                //记录下载失败
                m_cm.writeRecord(m_fileList.at(i)->user,m_fileList.at(i)->filename,"010");
            }
            break;
        }
    }
}

//根据传入的参数确定要执行的功能：分享、删除、显示属性
void MyFileWg::dealSelectdFile(QString cmd)
{
    QListWidgetItem *item = ui->listWidget->currentItem();
    if(NULL == item)
    {
        return;
    }
    for(int i = 0;i<m_fileList.size();++i)
    {
        if(m_fileList.at(i)->item == item)
        {
            if("分享" == cmd)
            {
                shareFile(m_fileList.at(i));
            }
            else if("删除" == cmd)
            {
                delFile(m_fileList.at(i));
            }
            else if("属性" == cmd)
            {
                getFileProperty(m_fileList.at(i));
            }
            break;
        }
    }
}
//给deal调用的几个函数提供JSON包
QByteArray MyFileWg::setDealFileJson(QString user, QString token, QString md5, QString filename)
{
    QMap<QString,QVariant> tmp;
    tmp.insert("user",user);
    tmp.insert("token",token);
    tmp.insert("md5",md5);
    tmp.insert("filename",filename);

    QJsonDocument json = QJsonDocument::fromVariant(tmp);
    if(json.isNull())
    {
        return "";
    }
    return json.toJson();
}
//分享文件
void MyFileWg::shareFile(FileInfo *info)
{
/*
根据本地信息判断分享状态
若未分享则获取登录信息的单例，和当前文件的信息组成json包，发送给服务器进行处理
接收服务器传来的信息，解析获得状态码，根据不同的状态码去做不同处理：修改本地状态、报错、验证错误退出登录等
*/
    if(1 == info->shareStatus)//判断是否已分享
    {
        QMessageBox::warning(this,"此文件已经分享","此文件已分享");
        return;
    }
    QNetworkRequest request;//设置请求对象
    //#include "common/logininfoinstance.h"
    LoginInfoInstance *login = LoginInfoInstance::getInstance();//获取登录的单例
    QString url = QString("http://%1:%2/dealfile?cmd=share").arg(login->getIp()).arg(login->getPort());
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QByteArray data = setDealFileJson(login->getUser(),login->getToken(),info->md5,info->filename);
    QNetworkReply *reply = m_manager->post(request,data);
    if(NULL == reply){return;}

    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(QNetworkReply::NoError != reply->error())
        {
            reply->deleteLater();//释放
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();//释放
        //获取状态码，根据状态码进行不同操作
        if("010" == m_cm.getCode(array))//common.h
        {
            info->shareStatus = 1;//设置状态码
            QMessageBox::information(this,"分享成功",QString("文件[%1]分享成功").arg(info->filename));
        }
        else if("011" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"分享失败",QString("文件[%1]分享失败").arg(info->filename));
        }
        else if("012" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"分享失败",QString("文件[%1]已被别人分享过").arg(info->filename));
        }
        else if("111" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"账户验证异常","请重新登陆");
            emit loginAgainSignal();//发送信号重新登录
            return;
        }
    });
}
//删除文件
void MyFileWg::delFile(FileInfo *info)
{
/*
获取登录单例，获取Ip和port
组成json包，发送给服务器
接收返回的状态码，删除成功则移除本地显示的图标和fileinfo中的对象
失败则提示失败，登陆状态异常则返回登录页重新登陆
*/
    QNetworkRequest request;//请求对象
    LoginInfoInstance *login = LoginInfoInstance::getInstance();//
    QString url = QString("http://%1:%2/dealfile?cmd=del").arg(login->getIp().arg(login->getPort()));
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QByteArray data = setDealFileJson(login->getUser(),login->getToken(),info->md5,info->filename);
    QNetworkReply *reply = m_manager->post(request,data);
    if(NULL == reply)
    {
        return;
    }
    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(QNetworkReply::NoError != reply->error())
        {
            reply->deleteLater();
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();
        if("013" == m_cm.getCode(array))
        {
            QMessageBox::information(this,"文件删除成功","文件删除成功!!!");
            //删除当前listwidget的item
            for(int i = 0;i<m_fileList.size();++i)
            {
                if(info == m_fileList.at(i))
                {
                    QListWidgetItem *item = info->item;
                    ui->listWidget->removeItemWidget(item);
                    delete item;
                    m_fileList.removeAt(i);
                    delete info;
                    break;//必要
                }
            }
        }
        else if("014" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"文件删除失败","文件删除失败");
        }
        else if("111" == m_cm.getCode(array))
        {
            QMessageBox::warning(this,"账户异常","请重新登陆！！！");
            emit loginAgainSignal();//重新登录
            return;
        }
    });
}
//显示文件详细信息
void MyFileWg::getFileProperty(FileInfo *info)
{
    //#include "selfwidget/filepropertyinfo.h"
    FilePropertyInfo dlg;
    dlg.setInfo(info);
    dlg.exec();
}
//按照不同排序方式刷新文件列表
void MyFileWg::refreshFiles(MyFileWg::Display cmd)
{
    m_userFilesCount = 0;
    LoginInfoInstance * login = LoginInfoInstance::getInstance();
    QString url = QString("http;//%1:%2/myfiles?cmd=count").arg(login->getIp()).arg(login->getPort());
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QByteArray data = setGetCountJson(login->getUser(),login->getToken());
    QNetworkReply *reply = m_manager->post(request,data);
    if(NULL == reply)
    {
        return;
    }
    //
    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(QNetworkReply::NoError != reply->error())
        {
            reply->deleteLater();
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();
        QStringList list = getCountStatus(array);
        if(list.at(0) == "111")
        {
            QMessageBox::warning(this,"账户异常","请重新登录");
            emit loginAgainSignal();
            return;
        }
        //这里有问题，at返回的不是string
        m_userFilesCount = QString(list.at(1)).toLong();
        clearFileList();//清空文件列表
        if(m_userFilesCount > 0)
        {
            m_start = 0;
            m_count = 10;
            getUserFilesList(cmd);
        }
        else
        {
            refreshFileItems();//更新全部item
        }
    });
    //refreshFileItems();//更新全部item
}
//添加上传文件
void MyFileWg::addUploadFiles()
{
/**/
    emit gotoTransfer(TransferStatus::Uplaod);//切换到上传界面

    UploadTask *uploadList = UploadTask::getInstance();//获取上传列表单例
    if(NULL == uploadList)
    {
        return;//空则返回
    }
    QStringList list = QFileDialog::getOpenFileNames();

    for(int i = 0;i < list.size();++i)
    {
        qDebug()<<"MyFileWg::addUploadFiles()崩溃点1";
        int res = uploadList->appendUploadList(list.at(i));
        qDebug()<<"MyFileWg::addUploadFiles()崩溃点2";
        if(res == -2)//还有个-1是限制上传文件大小的，注释了
        {
            QMessageBox::warning(this,"文件添加失败","上传的文件已经在上传队列中");
        }
        else if(-3 == res)
        {
            QMessageBox::warning(this,"文件打开失败","文件打开失败");
        }
        else if(-4 == res)
        {
            QMessageBox::warning(this,"获取单例失败","获取上传单例失败");
        }
    }
    qDebug()<<"MyFileWg::addUploadFiles()";
}

// 下载文件处理，取出下载任务列表的队首任务，下载完后，再取下一个任务
void MyFileWg::downloadFilesAction()
{
    DownloadTask *p = DownloadTask::getInstance();
    if(NULL == p)
    {
        return;
    }
    if(p->isEmpty())
    {
        return;
    }
    if(p->isDownload())
    {
        return;
    }
    if(p->isShareTask() == true)
    {
        return;
    }
    DownloadInfo *tmp = p->takeTask();

    QUrl url = tmp->url;
    QFile *file = tmp->file;
    QString md5 = tmp->md5;
    QString user = tmp->user;
    QString fileName = tmp->filename;
    DataProgress *dp = tmp->dp;

    QNetworkReply *reply = m_manager->get(QNetworkRequest(url));
    if(NULL == reply)
    {
        p->dealDownloadTask();
        return;
    }
    connect(reply,&QNetworkReply::finished,[=]()
    {
        reply->deleteLater();
        p->dealDownloadTask();
        m_cm.writeRecord(user,fileName,"010");
        dealFilePv(md5,fileName);
    });
    connect(reply,&QNetworkReply::readyRead,[=]()
    {
        if(NULL == file)
        {
            file->write(reply->readAll());
        }
    });
    connect(reply,&QNetworkReply::downloadProgress,[=](qint64 bytesRead,qint64 totalBytes)
    {
        dp->setProgress(bytesRead/1024,totalBytes/1024);//设置进度条进度
    });
}
//向数据库添加下载次数
void MyFileWg::dealFilePv(QString md5, QString filename)
{
    QNetworkRequest request;
    LoginInfoInstance *login = LoginInfoInstance::getInstance();
    QString url = QString("http://%1:%2/dealfile?cmd=pv").arg(login->getIp()).arg(login->getPort());
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QByteArray data = setDealFileJson(login->getUser(),login->getToken(),md5,filename);
    QNetworkReply * reply = m_manager->post(request,data);
    if(NULL == reply)
    {
        return;
    }
    connect(reply,&QNetworkReply::finished,[=]()
    {
        if(reply->error() != QNetworkReply::NoError)
        {
            reply->deleteLater();
            return;
        }
        QByteArray array = reply->readAll();
        reply->deleteLater();
        if("016" == m_cm.getCode(array))
        {
            for(int i =0;i<m_fileList.size();++i)
            {
                FileInfo *info = m_fileList.at(i);
                if(info->md5 == md5 && info->filename == filename)
                {
                    int pv = info->pv;
                    info->pv = pv+1;
                    break;
                }
            }
        }
        else
        {
            qDebug()<<"下载文件pv字段处理失败";
        }
    });
}

//清空上传下载任务
void MyFileWg::clearAllTask()
{
    UploadTask *uploadList = UploadTask::getInstance();
    if(uploadList == NULL)
    {
        return;
    }
    uploadList->clearList();

    DownloadTask *p = DownloadTask::getInstance();
    if(NULL == p)
    {
        return;
    }
    p->clearList();
}

// 定时检查处理任务队列中的任务
void MyFileWg::checkTaskList()
{
    connect(&m_uploadFileTimer,&QTimer::timeout,[=]()
    {
        uploadFilesAction();//
    });
    m_uploadFileTimer.start(500);
    connect(&m_downloadTimer,&QTimer::timeout,[=]()
    {
        downloadFilesAction();//
    });
    m_downloadTimer.start(500);
}

//根据传递的参数决定要显示的右键菜单
void MyFileWg::showmenu(const QPoint &pos)
{
    //返回一个pos指向处项目的指针，null代表该处没有项目图标
    QListWidgetItem *item = ui->listWidget->itemAt(pos);
    if(NULL == item)
    {
        //在点击位置显示菜单
        m_menuEmpty->exec(QCursor::pos());
    }
    else
    {
        //存疑：选中图标，后面可能有别的操作
        ui->listWidget->setCurrentItem(item);
        //判断当前图标是不是"上传文件"
        if("上传文件" == item->text())
        {
            return;
        }
        m_menu->exec(QCursor::pos());
    }
}
